package com.xx.springboot.utils;

import com.mysql.jdbc.TimeUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * TODO:
 * </p>
 *
 * @author hcg
 * @date 2019/2/27 14:52
 * @className RedisSessionDao
 */
public class RedisSessionDao extends EnterpriseCacheSessionDAO {

    private static final int EXPIRE_TIME = 1800;
    private Logger logger = LoggerFactory.getLogger(RedisSessionDao.class);
    private static String prefix = "shiro-session:";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        this.logger.info("创建session: {}", session.getId());
        redisTemplate.opsForValue().set(prefix + sessionId.toString(), session);
        return sessionId;
    }

    /**
     * 获取session
     * @param sessionId
     * @return
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        this.logger.info("获取session:{}", sessionId);
        // 先从缓存中读取, 如果没有再去数据库中获取
        Session session = super.doReadSession(sessionId);
        if (session == null) {
            session = (Session) redisTemplate.opsForValue().get(prefix + sessionId.toString());
        }
        return session;
    }


    /**
     * 更新最后一次访问时间
     * @param session
     */
    @Override
    protected void doUpdate(Session session) {
        this.logger.info("获取session:{}", session.getId());
        super.doUpdate(session);
        String key = prefix + session.getId().toString();
        if (!redisTemplate.hasKey(key)) {
            redisTemplate.opsForValue().set(key, session);
        }
        redisTemplate.expire(key, EXPIRE_TIME, TimeUnit.SECONDS);

    }

    /**
     * 删除session
     * @param session
     */
    @Override
    protected void doDelete(Session session) {
        this.logger.info("获取session:{}", session.getId());
        super.doDelete(session);
        //删除session
        redisTemplate.delete(prefix + session.getId().toString());
    }
}
